package net.oschina.app.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.adapter.ListViewBlogAdapter;
import net.oschina.app.bean.Blog;
import net.oschina.app.bean.BlogList;
import net.oschina.app.bean.Notice;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import net.oschina.app.widget.NewDataToast;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class BaseBlogNewsListFragment extends MainPullToRefreshListFragment {
	private ListViewBlogAdapter lvBlogAdapter;
	private List<Blog> lvBlogData = new ArrayList<Blog>();
	private int lvBlogSumData;
	private Handler lvBlogHandler;
	private int curNewsCatalog;

	public BaseBlogNewsListFragment(int curNewsCatalog,
			OnBaseListFragmentResumeListener baseListFragmentResumeListener) {
		super(baseListFragmentResumeListener);
		this.curNewsCatalog = curNewsCatalog;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initBlogListView();
	}
	@Override
	public void onDestroyView() {
		lvBlogData.clear();
		super.onDestroyView();
	}
	/**
	 * 初始化博客列表
	 */
	private void initBlogListView() {
		lvBlogAdapter = new ListViewBlogAdapter(getActivity(),
				BlogList.CATALOG_LATEST, lvBlogData, R.layout.blog_listitem);
		listView.addFooterView(list_footer);// 添加底部视图 必须在setAdapter前
		listView.setAdapter(lvBlogAdapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击头部、底部栏无效
				if (view == list_footer)
					return;

				Blog blog = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					blog = (Blog) view.getTag();
				} else {
					TextView tv = (TextView) view
							.findViewById(R.id.blog_listitem_title);
					blog = (Blog) tv.getTag();
				}
				if (blog == null)
					return;

				// 跳转到博客详情
				UIHelper.showUrlRedirect(view.getContext(), blog.getUrl());
			}
		});
		listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {

				// 数据为空--不用继续下面代码了
				if (lvBlogData.isEmpty())
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(list_footer) == view
							.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(listView.getTag());
				if (scrollEnd && lvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					listView.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					list_foot_more.setText(R.string.load_ing);
					list_foot_progress.setVisibility(View.VISIBLE);
					// 当前pageIndex
					int pageIndex = lvBlogSumData / AppContext.PAGE_SIZE;
					loadLvBlogData(curNewsCatalog, pageIndex, lvBlogHandler,
							UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});

		lvBlogHandler = this.getLvHandler(listView, lvBlogAdapter,
				list_foot_more, list_foot_progress, AppContext.PAGE_SIZE);
	}

	/**
	 * 线程加载博客数据
	 * 
	 * @param catalog
	 *            分类
	 * @param pageIndex
	 *            当前页数
	 * @param handler
	 *            处理器
	 * @param action
	 *            动作标识
	 */
	private void loadLvBlogData(final int catalog, final int pageIndex,
			final Handler handler, final int action) {
		mPullToRefreshAttacher.setRefreshing(true);
		new Thread() {
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH
						|| action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				String type = "";
				switch (catalog) {
				case BlogList.CATALOG_LATEST:
					type = BlogList.TYPE_LATEST;
					break;
				case BlogList.CATALOG_RECOMMEND:
					type = BlogList.TYPE_RECOMMEND;
					break;
				}
				try {
					BlogList list = appContext.getBlogList(type, pageIndex,
							isRefresh);
					msg.what = list.getPageSize();
					msg.obj = list;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				msg.arg2 = UIHelper.LISTVIEW_DATATYPE_BLOG;
				if (curNewsCatalog == catalog)
					handler.sendMessage(msg);
			}
		}.start();
	}

	/**
	 * listview数据处理
	 * 
	 * @param what
	 *            数量
	 * @param obj
	 *            数据
	 * @param objtype
	 *            数据类型
	 * @param actiontype
	 *            操作类型
	 * @return notice 通知信息
	 */
	private Notice handleLvData(int what, Object obj, int objtype,
			int actiontype) {
		Notice notice = null;
		switch (actiontype) {
		case UIHelper.LISTVIEW_ACTION_INIT:
		case UIHelper.LISTVIEW_ACTION_REFRESH:
		case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
			int newdata = 0;// 新加载数据-只有刷新动作才会使用到
			switch (objtype) {
			case UIHelper.LISTVIEW_DATATYPE_BLOG:
				BlogList blist = (BlogList) obj;
				notice = blist.getNotice();
				lvBlogSumData = what;
				if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH) {
					if (lvBlogData.size() > 0) {
						for (Blog blog1 : blist.getBloglist()) {
							boolean b = false;
							for (Blog blog2 : lvBlogData) {
								if (blog1.getId() == blog2.getId()) {
									b = true;
									break;
								}
							}
							if (!b)
								newdata++;
						}
					} else {
						newdata = what;
					}
				}
				lvBlogData.clear();// 先清除原有数据
				lvBlogData.addAll(blist.getBloglist());
				break;
			}
			if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH) {
				// 提示新加载数据
				if (newdata > 0) {
					NewDataToast
							.makeText(
									getActivity(),
									getString(R.string.new_data_toast_message,
											newdata), appContext.isAppSound())
							.show();
				} else {
					NewDataToast.makeText(getActivity(),
							getString(R.string.new_data_toast_none), false)
							.show();
				}
			}
			break;
		case UIHelper.LISTVIEW_ACTION_SCROLL:
			switch (objtype) {
			case UIHelper.LISTVIEW_DATATYPE_BLOG:
				BlogList blist = (BlogList) obj;
				notice = blist.getNotice();
				lvBlogSumData += what;
				if (lvBlogData.size() > 0) {
					for (Blog blog1 : blist.getBloglist()) {
						boolean b = false;
						for (Blog blog2 : lvBlogData) {
							if (blog1.getId() == blog2.getId()) {
								b = true;
								break;
							}
						}
						if (!b)
							lvBlogData.add(blog1);
					}
				} else {
					lvBlogData.addAll(blist.getBloglist());
				}
				break;
			}
			break;
		}
		return notice;
	}

	/**
	 * 获取listview的初始化Handler
	 * 
	 * @param lv
	 * @param adapter
	 * @return
	 */
	protected Handler getLvHandler(final ListView lv,
			final BaseAdapter adapter, final TextView more,
			final ProgressBar progress, final int pageSize) {
		return new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what >= 0) {
					// listview数据处理
					Notice notice = handleLvData(msg.what, msg.obj, msg.arg2,
							msg.arg1);

					if (msg.what < pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_FULL);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_full);
					} else if (msg.what == pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);

						// 特殊处理-热门动弹不能翻页
						// if (lv == lvTweet) {
						// TweetList tlist = (TweetList) msg.obj;
						// if (lvTweetData.size() == tlist.getTweetCount()) {
						// lv.setTag(UIHelper.LISTVIEW_DATA_FULL);
						// more.setText(R.string.load_full);
						// }
						// }
					}
					// 发送通知广播
					if (notice != null) {
						UIHelper.sendBroadCast(lv.getContext(), notice);
					}
					// 是否清除通知信息
					// if (isClearNotice) {
					// ClearNotice(curClearNoticeType);
					// isClearNotice = false;// 重置
					// curClearNoticeType = 0;
					// }
				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
					more.setText(R.string.load_error);
					((AppException) msg.obj).makeToast(getActivity());
				}
				if (adapter.getCount() == 0) {
					lv.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					more.setText(R.string.load_empty);
				}
				progress.setVisibility(ProgressBar.GONE);
				mPullToRefreshAttacher.setRefreshComplete();
				if (msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH) {
					// getFragmentActivity().setActionBarSubtitle(getString(R.string.pull_to_refresh_update)
					// + new Date().toLocaleString());
					lv.setSelection(0);
				} else if (msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG) {
					lv.setSelection(0);
				}
			}
		};
	}

	@Override
	public void onRefreshStarted(View view) {
		loadLvBlogData(curNewsCatalog, 0, lvBlogHandler,
				UIHelper.LISTVIEW_ACTION_REFRESH);
	}

	@Override
	public void showList() {
		if(!isHasInit()) {
			loadLvBlogData(curNewsCatalog, 0, lvBlogHandler,
					UIHelper.LISTVIEW_ACTION_INIT);
			setHasInit(true);
		}
	}

}
